<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import { getTableListApi, saveTableApi, delTableListApi,getGroupNameApi } from '@/api/group'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/group/types'
import { ref, unref, reactive, computed, onMounted, onUnmounted } from 'vue'
import Write from './components/Write.vue'
//import Detail from './components/Detail.vue'
import OperatorList from './components/OperatorList.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
//import { pad } from 'lodash-es'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      page: unref(currentPage),
      pagesize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.items,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('tableGroupManager.id'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                padding: 8px;
                margin: -8px;
                align-items: center;
                transition: background-color 0.2s;
              "
              onMouseenter={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = '#f5f7fa'
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = 'transparent'
                }
              }}
              onClick={() => action(data.row, 'edit')}
            >
              {data.row.id}
            </div>
          )
        }
      }
    }
  },
    {
    field: 'search',
    hidden: true,
    label: t('tableGroupManager.search'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'name',
    label: t('tableGroupManager.grpname'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
      // componentProps: {
      //   style: {
      //     width: '500px',
      //     height: '40px',
      //     fontSize: '16px'
      //   }
      // }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'leaderName',
    label: t('tableGroupManager.leaderName'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'leader',
    label: t('tableGroupManager.leaderName'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '500px',
          height: '40px',
          fontSize: '16px'
        },
        props: {
          label: 'account',
          value: 'id'
        }
      },
      optionApi: async () => {
        const res = await getGroupNameApi()
        return res.data.items
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'income',
    label: t('tableGroupManager.income'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const formatToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return numValue.toFixed(2)
          }
          return <span>{formatToTwoDecimals(data.row.income)}</span>
        }
      }
    }
  },
  {
    field: 'balance',
    label: t('tableGroupManager.balance'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const formatToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return numValue.toFixed(2)
          }
          return <span>{formatToTwoDecimals(data.row.balance)}</span>
        }
      }
    }
  },
  {
    field: 'expenditure',
    label: t('tableGroupManager.expenditure'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const formatToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return numValue.toFixed(2)
          }
          return <span>{formatToTwoDecimals(data.row.expenditure)}</span>
        }
      }
    }
  },
  {
    field: 'lastexp',
    label: t('tableGroupManager.lastexp'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const formatToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return numValue.toFixed(2)
          }
          return <span>{formatToTwoDecimals(data.row.lastexp)}</span>
        }
      }
    }
  },
  {
    field: 'avgexp',
    label: t('tableGroupManager.avgexp'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const formatToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return numValue.toFixed(2)
          }
          return <span>{formatToTwoDecimals(data.row.avgexp)}</span>
        }
      }
    }
  },
  {
    field: 'ctime',
    label: t('tableGroupManager.ctime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
   {
    field: 'oprs',
    label: t('tableGroupManager.grpNum'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                align-items: center;
                transition: background-color 0.2s;
              "
              onMouseenter={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = '#f5f7fa'
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = 'transparent'
                }
              }}
              onClick={() => action(data.row, 'grpOperator')}
            >
              {Array.isArray(data.row.oprs) ? data.row.oprs.length : 0}
            </div>
          )
        }
      }
    }
  },
  {
    field: 'status',
    label: t('tableGroupManager.status'),
    search: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const status = data.row.status
          return (
            <>
              <ElTag type={status === 0 ? 'success' : 'danger'}>
                {status === 0 ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      colProps: {
        span: 24
      },
      componentProps: {
        // style: {
        //   width: '500px',
        //   height: '40px',
        //   fontSize: '16px'
        // }
        options: [
          {
            label: '启用',
            value: 0
          },
          {
            label: '禁用',
            value: 1
          }
        ]
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'remarks',
    label: t('tableGroupManager.remarks'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
      // componentProps: {
      //   style: {
      //     width: '500px',
      //     height: '40px',
      //     fontSize: '16px'
      //   }
      // }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },

  // {
  //   field: 'action',
  //   width: '260px',
  //   label: t('tableDemo.action'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <>
  //             <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
  //               {t('exampleDemo.edit')}
  //             </BaseButton>
  //             <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
  //               {t('exampleDemo.detail')}
  //             </BaseButton>
  //             <BaseButton type="danger" onClick={() => delData(data.row)}>
  //               {t('exampleDemo.del')}
  //             </BaseButton>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

// 响应式宽度：手机端350px，PC端500px
const isMobile = ref(false)
const dialogWidth = computed(() => (isMobile.value ? '350px' : '500px'))

const updateMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

onMounted(() => {
  updateMobile()
  window.addEventListener('resize', updateMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateMobile)
})

const AddAction = () => {
  dialogTitle.value = t('tableGroupManager.addGroup')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TableData, type: string) => {
  if (type === 'edit') {
    dialogTitle.value = t('tableGroupManager.edit')
  } else {
    dialogTitle.value = row.name + t('tableGroupManager.grpMembers')
  }
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams"/>

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton> -->
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total,
        layout: '->, total, sizes, prev, pager, next, jumper'
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="dialogWidth" :maxHeight="250">
    <Write
      v-if="actionType === 'edit'|| actionType === 'add'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <OperatorList
      v-if="actionType === 'grpOperator'"
      :current-row="currentRow"
    />

    <template #footer>
      <div v-if="actionType === 'grpOperator'">
        <!-- <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton> -->
      </div>
      <div v-else-if="actionType === 'edit'" style="display: flex; justify-content: space-between; align-items: center;">
        <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(currentRow)">
          {{ t('exampleDemo.del') }}
        </BaseButton> -->
        <div>
          <BaseButton
            type="primary"
            :loading="saveLoading"
            @click="save"
            style="margin-right: 8px;"
          >
            {{ t('exampleDemo.save') }}
          </BaseButton>
          <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
        </div>
      </div>
      <div v-else>
        <BaseButton
          type="primary"
          :loading="saveLoading"
          @click="save"
          style="margin-right: 8px;"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </div>
    </template>
  </Dialog>
</template>
<!-- <style scoped>
:deep(.el-form-item__label) {
  font-size: 16px !important;
  padding-top: 10px !important;
}
</style> -->
